package priv.mill.simple;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class PackageDecoder extends ByteToMessageDecoder{

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf b, List<Object> l) throws Exception {
		byte[] bs = new byte[b.readableBytes()];
		b.readBytes(bs);
		Object object = fromBytes(bs);
		l.add(object);
	}

	public Object fromBytes(byte[] bs) throws IOException, ClassNotFoundException {
		Object object;
		try (ByteArrayInputStream bIn = new ByteArrayInputStream(bs);
				ObjectInputStream oIn = new ObjectInputStream(bIn);){
			object = oIn.readObject();
			return object;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
